from ..log import log_gui
from ..screen import BaseScreenWidget
from ..rect import Rect
import gtk

class Form(BaseScreenWidget):
  def __init__(self, x, y, layout, background):
    """background: A gui.Background"""
    BaseScreenWidget.__init__(self, x, y, layout.GetWidth(), layout.GetHeight())
    layout.SetPositions()
    # There may be None items for containers.
    self._items = layout.GetItems()
    for item in self._items:
      if item:
        item.SetForm(self)
    self._button_down_item = None
    self._background = background

  def Draw(self, screen, window, clip_rect):
    """Do not call this if you are a form item. If you want to redraw during a
    callback (e.g., OnButtonDown) use form.Paint() (implemented in
    BaseScreenWidget)."""
    assert window is not None
    rect = Rect((
      self.rect.left + screen.rect.left,
      self.rect.top + screen.rect.top,
      self.rect.width,
      self.rect.height))

    self._background.Draw(
        window,
        rect,
        clip_rect)

    # Draw each item.
    for item in self._items:
      if item and not item.GetHidden():
        item.Draw(screen, window, rect, clip_rect)

  def OnButtonDown(self, event, data):
    #x, y = event.x, event.y
    x, y, state = event.window.get_pointer()
    x -= self.rect.left
    y -= self.rect.top
    log_gui('Form.OnButtonDown at ',x,',',y)
    for item in self._items:
      if item:
        log_gui('  Try', item,'at',item.rect)
        if item.GetInteractive() and item.rect.collidepoint((x, y)):
          log_gui('**HIT**')
          self._button_down_item = item
          item.OnButtonDown(self, event, data, (x, y))
          return

  def OnButtonUp(self, event, data):
    x, y, state = event.window.get_pointer()
    if self._button_down_item:
      log_gui("Running item", self._button_down_item, " OnButtonUp.")
      self._button_down_item.OnButtonUp(self, event, data, (x, y))
    else:
      log_gui("No button down item")
    self._button_down_item = None

  def OnMouseMove(self, event, data):
    x, y, state = event.window.get_pointer()
    for item in self._items:
      if item and item.GetInteractive() and item.rect.collidepoint((x, y)):
        item.OnMouseMove(self, event, data, (x, y))
        return

  def Update(self):
    for item in self._items:
      if item:
        item.Update()

